import React, { useState, useEffect } from 'react';

interface LLMModel {
  id: number;
  name: string;
  provider: string;
  llm_model_id: string;
  max_tokens: number;
  temperature: number;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

interface ModelSelectorProps {
  onModelSelect: (model: LLMModel) => void;
  selectedModel: LLMModel | null;
}

const ModelSelector: React.FC<ModelSelectorProps> = ({ onModelSelect, selectedModel }) => {
  const [models, setModels] = useState<LLMModel[]>([]);
  const [loading, setLoading] = useState(true);
  const [isOpen, setIsOpen] = useState(false);

  useEffect(() => {
    // 检查是否存在有效的token
    const token = localStorage.getItem('access_token');
    if (!token) {
      return;
    }
    
    // 获取模型列表
    fetch('/api/v1/llm/models', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    .then(response => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error('Failed to fetch models');
      }
    })
    .then(data => {
      setModels(data);
      setLoading(false);
    })
    .catch(error => {
      console.error('Error fetching models:', error);
      setLoading(false);
    });
  }, []);

  const handleToggle = () => {
    setIsOpen(!isOpen);
  };

  const handleModelSelect = (model: LLMModel) => {
    onModelSelect(model);
    setIsOpen(false);
  };

  if (loading) {
    return (
      <div style={{ 
        position: 'relative', 
        width: '100%', 
        height: '40px', 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center',
        color: 'white',
        fontSize: '1rem'
      }}>
        加载中...
      </div>
    );
  }

  return (
    <div style={{
      position: 'relative',
      width: '100%',
      color: 'white'
    }}>
      <div 
        onClick={handleToggle}
        style={{
          padding: '10px',
          backgroundColor: 'rgba(0, 0, 0, 0.4)',
          backdropFilter: 'blur(15px)',
          border: '1px solid rgba(255, 255, 255, 0.1)',
          borderRadius: '10px',
          cursor: 'pointer',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}
      >
        <span>{selectedModel ? selectedModel.name : '请选择模型'}</span>
        <span>{isOpen ? '▲' : '▼'}</span>
      </div>
      
      {isOpen && (
        <div style={{
          position: 'absolute',
          top: '100%',
          left: 0,
          right: 0,
          marginTop: '5px',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          backdropFilter: 'blur(15px)',
          border: '1px solid rgba(255, 255, 255, 0.1)',
          borderRadius: '10px',
          maxHeight: '200px',
          overflowY: 'auto',
          zIndex: 1000
        }}>
          {models.map(model => (
            <div 
              key={model.id}
              onClick={() => handleModelSelect(model)}
              style={{
                padding: '10px',
                cursor: 'pointer',
                borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
                '&:hover': {
                  backgroundColor: 'rgba(97, 220, 163, 0.3)'
                }
              }}
            >
              {model.name}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default ModelSelector;